package org.codehaus.activemq.filter;

import java.util.ArrayList;
import java.util.List;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;

public class DestinationPath
{
  public static String[] getDestinationPaths(String subject)
  {
    List list = new ArrayList();
    int previous = 0;
    int lastIndex = subject.length() - 1;
    while (true) {
      int idx = subject.indexOf('.', previous);
      if (idx < 0) {
        list.add(subject.substring(previous, lastIndex + 1));
        break;
      }
      list.add(subject.substring(previous, idx));
      previous = idx + 1;
    }
    String[] answer = new String[list.size()];
    list.toArray(answer);
    return answer;
  }

  public static String[] getDestinationPaths(Message message) throws JMSException {
    return getDestinationPaths(message.getJMSDestination());
  }

  public static String[] getDestinationPaths(Destination destination) {
    return getDestinationPaths(destination.toString());
  }

  public static String toString(String[] paths)
  {
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < paths.length; i++) {
      if (i > 0) {
        buffer.append(".");
      }
      String path = paths[i];
      if (path == null) {
        buffer.append("*");
      }
      else {
        buffer.append(path);
      }
    }
    return buffer.toString();
  }
}